package com.xms.plugin.service;

import com.xms.core.SpringContextHolder;
import com.xms.core.data.Entity;
import com.xms.core.enums.OperationStage;
import com.xms.core.enums.OperationType;
import com.xms.plugin.core.IEntityPlugin;
import com.xms.plugin.core.PluginExecutionContext;
import com.xms.plugin.entity.EntityPlugin;
import com.xms.schema.entity.Attribute;
import com.xms.security.identity.ICurrentUser;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * EntityPluginExecutor
 * </p>
 *
 * @author migo
 * @since 2021/10/15
 */
@Service
public class EntityPluginExecutor implements IEntityPluginExecutor {
    private IEntityPluginFinderService _entityPluginFinderService;
    private IEntityPluginFileProvider _entityPluginFileProvider;
    private ICurrentUser _currentUser;

    @Autowired
    public void EntityPluginExecutor(IEntityPluginFinderService entityPluginFinderService,
                                     IEntityPluginFileProvider entityPluginFileProvider,
                                     ICurrentUser currentUser) {
        _entityPluginFinderService = entityPluginFinderService;
        _entityPluginFileProvider = entityPluginFileProvider;
        _currentUser = currentUser;
    }

    @Override
    public void execute(OperationType op, OperationStage stage, Entity entity, com.xms.schema.entity.Entity entityMetadata, List<Attribute> attributeMetadatas) throws Exception {
        // 获取当前实体已注册插件
        List<EntityPlugin> currentEntityPlugins = _entityPluginFinderService.getByEntityId(entityMetadata.getEntityid(), op.value());
        if (CollectionUtil.isEmpty(currentEntityPlugins)) {
            return;
        }
        for (EntityPlugin pluginInfo : currentEntityPlugins) {
            IEntityPlugin pg = this.getInstance(pluginInfo);
            if(pg == null) continue;
            PluginExecutionContext context = new PluginExecutionContext();
            context.messageName = op;
            context.stage = stage;
            context.target = entity;
            context.user = _currentUser.getUser();
            context.entityMetadata = entityMetadata;
            context.attributeMetadatas = attributeMetadatas;
            pg.execute(context);
        }
    }

    /**
     * 创建插件实例
     *
     * @param entity
     * @return
     */
    private IEntityPlugin getInstance(EntityPlugin entity) throws ClassNotFoundException {
        IEntityPlugin _instance = null;
        if (_entityPluginFileProvider.loadAssembly(entity)) {
            //_instance = Class.forName(entity.getClassname()).newInstance();
            try {
                _instance = (IEntityPlugin) SpringContextHolder.getApplicationContext().getBean(Class.forName(entity.getClassname()));
            }catch(Exception e){

            }
        }
        return _instance;
    }
}
